package com.market.dao.jpa;

import java.util.List;

import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.market.dao.MessageDao;
import com.market.domain.Location;
import com.market.domain.Message;
import com.market.domain.Picture;
import com.market.domain.User;
@Repository("messageDao")
public class MessageDaoJpa extends GenericDaoJpa<Message, Long> implements
		MessageDao {

	public MessageDaoJpa() {
		super(Message.class);
	}
	
	public List<Message> findAllBlogs() {
		String sql = "select message.* from message where type = '" + Message.TYPE.BLOG + "' order by id desc";
		Query query = this.em.createNativeQuery(sql, Message.class);
		List<Message> messages = query.getResultList();
		for(Message message:messages){
			List<Picture> pictures = this.findPictures(message);
			message.setPictures(pictures);
//			message.setUsers(this.findUsers(message));
		}
		return messages;
	}

	public void remove(Message message) {
		if (this.findById(message.getId()) == null) {
			log.debug(this.getClass() + " Message with id " + message.getId()
					+ " is not found, can not be deleted");
		} else {
			log.debug(this.getClass() + " Message with id " + message.getId()
					+ " is found, will be deleted");
			super.removeById(message.getId());
		}
	}

	public List<User> findUsers(Message message) {
		String sql = "select user.* from user, message_user where user.id=message_user.users_id "
				+ " and message_user.messages_id=" + message.getId();
		Query query = this.em.createNativeQuery(sql, User.class);
		List<User> users = query.getResultList();
		return users;
	}
	
	public List<Location> findLocations(Message message) {
		String sql = "select location.* from location, message_location where location.id=message_location.locations_id "
				+ " and message_location.messages_id=" + message.getId();
		Query query = this.em.createNativeQuery(sql, Location.class);
		List<Location> locations = query.getResultList();
		return locations;
	}

	public List<Picture> findPictures(Message message) {
		String sql = "select picture.* from picture, message_picture where picture.id=message_picture.pictures_id "
				+ " and message_picture.message_id=" + message.getId();
		Query query = this.em.createNativeQuery(sql, Picture.class);
		List<Picture> pictures = query.getResultList();
		return pictures;
	}
}
